/*
 * Copyright (c) 2015, 张涛.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sudworth.themvp.presenter;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.sudworth.themvp.model.IModel;
import com.sudworth.themvp.view.IDelegate;
import com.sudworth.themvp.annotation.Mvp;

import org.jetbrains.annotations.NotNull;

import javax.inject.Inject;

/**
 * Presenter base class for Fragment
 * Presenter层的实现基类
 *
 * @param <T> View delegate class type
 * @author kymjs (http://www.kymjs.com/) on 10/23/15.
 */
public abstract class FragmentPresenter<T extends IDelegate, M extends IModel> extends Fragment {

    @Inject
    protected T viewDelegate;

    @Inject
    protected M mModel;

    public FragmentPresenter() {
        if(canMvp()) return;
        Mvp annotation = getClass().getAnnotation(Mvp.class);
        viewDelegate = createIDelegateInstance(annotation);
        mModel = createIModelInstance(annotation);
    }

    protected boolean canViewBinding() {
        return false;
    }

    protected View onResetContentView() {
        return null;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewDelegate.setActivity(requireActivity());
    }

    @Nullable
    @Override
    public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        viewDelegate.create(inflater, container, savedInstanceState);
        if(canViewBinding()) {
            return onResetContentView();
        } else {
            return viewDelegate.getRootView();
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        onConfigView(view, savedInstanceState);
    }

    protected void onConfigView(View view, @Nullable Bundle savedInstanceState) {
        viewDelegate.setFragmentManager(getChildFragmentManager());
        viewDelegate.initWidget();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        bindEvenListener();
    }

    @Override
    public void onStart() {
        super.onStart();
        viewDelegate.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        viewDelegate.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        viewDelegate.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        viewDelegate.onStop();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        viewDelegate.onHiddenChanged(hidden);
    }

    protected void bindEvenListener() {
    }

    @Override
    public void onCreateOptionsMenu(@NotNull Menu menu, @NotNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        if (viewDelegate.getOptionsMenuId() != 0) {
            inflater.inflate(viewDelegate.getOptionsMenuId(), menu);
        }
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        if(canMvp()) return;
        Mvp annotation = getClass().getAnnotation(Mvp.class);
        if (viewDelegate == null) {
            viewDelegate = createIDelegateInstance(annotation);
        }
        if(mModel == null) {
            mModel = createIModelInstance(annotation);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (viewDelegate != null) {
            viewDelegate.destroy();
            viewDelegate = null;
        }
        if (mModel != null) {
            mModel.onDestroy();
            mModel = null;
        }
    }

    private M createIModelInstance(@NonNull Mvp annotation) {
        if (!isIModel(annotation)) {
            StringBuilder sb = new StringBuilder(this.getClass().getName());
            sb.append("-> ")
                    .append(annotation.view().getName())
                    .append(": 必须是IModel的实现类");
            throw new RuntimeException(sb.toString());
        }
        M m;
        try {
           m =  (M) annotation.model().newInstance();
        } catch (Exception e) {
            throw new RuntimeException("create IModel error: " + e.toString());
        }
        return m;
    }

    private T createIDelegateInstance(@NonNull Mvp annotation) {
        if (!isIDelegate(annotation)) {
            StringBuilder sb = new StringBuilder(this.getClass().getName());
            sb.append("-> ")
                    .append(annotation.view().getName())
                    .append(": 必须是IDelegate的实现类");
            throw new RuntimeException(sb.toString());
        }
        T t;
        try {
            t = (T) annotation.view().newInstance();
        } catch (Exception e) {
            throw new RuntimeException("create IDelegate error: " + e.toString());
        }
        return t;
    }

    private boolean isIModel(@NonNull Mvp annotation) {
        return IModel.class.isAssignableFrom(annotation.model());
    }

    private boolean isIDelegate(@NonNull Mvp annotation) {
        return IDelegate.class.isAssignableFrom(annotation.view());
    }

    private boolean canMvp() {
        return null == getClass().getAnnotation(Mvp.class);
    }
}
